package com.eostoken.eos_wallet.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.FragmentUtils;
import com.eostoken.eos_wallet.R;
import com.fredy.mvp.BaseMvpActivity;
import com.fredy.mvp.BaseMvpFragment;
import com.fredy.mvp.BasePresenter;
import com.fredy.mvp.BaseView;
import com.fredy.mvp.Model;

import butterknife.ButterKnife;


public abstract class BaseFragment<M extends Model, V extends BaseView, P extends BasePresenter>
        extends BaseMvpFragment<M, V, P> implements BaseView {

    /**
     * 用户设置的ContentView
     */
    protected View mContentView;
    /**
     * View有没有加载过
     */
    protected boolean isViewInitiated;
    /**
     * 页面是否可见
     */
    protected boolean isVisibleToUser;
    /**
     * 是不是加载过
     */
    protected boolean isDataInitiated;


    protected Context mContext;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        //在配置变化的时候将这个fragment保存下来
//        setRetainInstance(true);
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mContentView == null) {
            mContentView = createContentView(container);
        }
        ButterKnife.bind(this, mContentView);
        return mContentView;
    }

    public View getView() {
        return mContentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!isViewInitiated) {
            initData();
            initTitle();
            initView(view);
        }
        isViewInitiated = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        lazyLoad();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onDestroy() {
        mActivity = null;
        mContentView = null;
        isViewInitiated = false;
        hideLoading();
        super.onDestroy();
    }

    /**
     * 创建View
     */
    private View createContentView(ViewGroup parent) {
        View contentView = getLayoutInflater().inflate(getContentLayout(), parent, false);
        return contentView;
    }

    protected abstract int getContentLayout();

    /**
     * 如果要创建标题
     */
    protected void initTitle() {

    }

    /**
     * 初始化数据，包括上个页面传递过来的数据在这个方法做
     */
    protected abstract void initData();

    /**
     * 初始化View
     */
    protected abstract void initView(View contentView);

    /**
     * 懒加载，Fragment可见的时候调用这个方法，而且只调用一次
     */
    protected void lazyLoad() {
        if (isVisibleToUser && isViewInitiated && (!isDataInitiated)) {
            isDataInitiated = true;
            initData();
        }
    }


    /**
     * 打开Activity
     */
    public final void startActivity(Class<?> clazz) {
        startActivity(clazz, null);
    }

    /**
     * 打开Activity
     */
    public final void startActivity(Class<?> clazz, @Nullable Bundle options) {
        Intent intent = new Intent(getAppActivity(), clazz);
        if (options != null) {
            intent.putExtras(options);
        }
        startActivity(intent);
    }

    /**
     * 获取当前的Activity
     */
    public final Activity getAppActivity() {
        return mActivity;
    }

    /**
     * 设置TextView
     */
    public void setText(TextView textView, CharSequence text) {
        if (textView != null && text != null) {
            textView.setText(text);
        }
    }

    /**
     * 闭关页面
     */
    public void finish() {
        if (mActivity != null) {
            mActivity.finish();
        }
    }


    @Override
    public void showLoading() {
        BaseActivity activity = (BaseActivity) getActivity();
        if (activity instanceof BaseMvpActivity) {
            activity.showLoading();
        }
    }

    @Override
    public void showNetError() {

    }

    @Override
    public void hideLoading() {
        BaseActivity activity = (BaseActivity) getActivity();
        if (!isInvalidContext()) {
            activity.hideLoading();
        }
    }


    public void showTipDialog(String msg) {
        BaseActivity activity = (BaseActivity) getActivity();
        if (!isInvalidContext()) {
            activity.showTipDialog(msg);
        }
    }

    public void popOrFinish() {
        if (getFragmentManager().getBackStackEntryCount() < 1) {
            finish();
        } else {
            FragmentUtils.pop(getActivity().getSupportFragmentManager());
        }
    }

    public View getEmptyView(int mipmap, String tip, ViewGroup viewGroup) {
        View view = getLayoutInflater().inflate(R.layout.view_empty, viewGroup, false);
        AppCompatImageView mIv = view.findViewById(R.id.iv_empty);
        mIv.setImageResource(mipmap);
        AppCompatTextView mTvTip = view.findViewById(R.id.tv_tip);
        mTvTip.setText(tip);
        return view;
    }


//    public void showTipSingleButtonDialog(String text, BaseActivity.TipDialogConfirmListener listener) {
//        BaseActivity activity = (BaseActivity) getActivity();
//        if (activity instanceof BaseMvpActivity) {
//            activity.showTipDialog(text, listener);
//        }
//    }


//    public void showTwoButtonDialog(String text, String leftBtn, String rightBtn, BaseActivity.TwoBtnDialogListener listener) {
//        BaseActivity activity = (BaseActivity) getActivity();
//        if (activity instanceof BaseMvpActivity) {
//            activity.showTwoBtnDialog(text, leftBtn, rightBtn, listener);
//        }
//    }


    @Override
    public void onResume() {
        super.onResume();
        monitor();
    }

    private void monitor() {
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                    // 监听到返回按钮点击事件
                    popOrFinish();
                    return true;
                }
                return false;
            }
        });
    }

    private boolean isInvalidContext() {
        if (getActivity() == null) {
            return true;
        }
        return (getActivity().isDestroyed() || getActivity().isFinishing());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        unbindDrawables(getView());
    }

    private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
            view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            ((ViewGroup) view).removeAllViews();
        }
    }
}
